package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private ApartmentFacilityService apartmentFacilityService;

    @Autowired
    private ApartmentFacilityMapper apartmentFacilityMapper;

    @Autowired
    private ApartmentLabelService apartmentLabelService;

    @Autowired
    private ApartmentLabelMapper apartmentLabelMapper;

    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;

    @Autowired
    private ApartmentFeeValueMapper apartmentFeeValueMapper;

    @Autowired
    private LabelInfoMapper labelInfoMapper;

    @Autowired
    private FacilityInfoMapper facilityInfoMapper;

    @Autowired
    private FeeValueMapper feeValueMapper;

    @Autowired
    private RoomInfoService roomInfoService;

    @Autowired
    private RoomInfoMapper roomInfoMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {

        //判断当前请求是新增还是更新(如果id是null，那么就是新增，反之就是更新)
        boolean isUpdate = apartmentSubmitVo.getId() != null;

        //保存公寓基本信息(保存一定要放在判断的后面)
        this.saveOrUpdate(apartmentSubmitVo);

        if (isUpdate) {
            //删除公寓图片(实体)，根据类型和id来删
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, apartmentSubmitVo.getId());
            graphInfoMapper.delete(graphInfoLambdaQueryWrapper);
//            graphInfoService.remove(graphInfoLambdaQueryWrapper);

            //删除公寓配套(关联)
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, apartmentSubmitVo.getId());
            apartmentFacilityMapper.delete(apartmentFacilityLambdaQueryWrapper);

            //删除公寓标签(关联)
            LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, apartmentSubmitVo.getId());
            apartmentLabelMapper.delete(apartmentLabelLambdaQueryWrapper);

            //删除公寓杂费值(关联)
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, apartmentSubmitVo.getId());
            apartmentFeeValueMapper.delete(apartmentFeeValueLambdaQueryWrapper);
        }

        //保存公寓图片(实体)
        //得到图片的信息
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        //首先进行健壮性的判断
        if (!CollectionUtils.isEmpty(graphVoList)) {
            ArrayList<GraphInfo> graphInfoArrayList = new ArrayList<>();
            //将vo转为Info
            graphVoList.forEach(graphVo -> {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfoArrayList.add(graphInfo);
            });
            //批量保存
            graphInfoService.saveBatch(graphInfoArrayList);
        }

        //保存公寓配套(关联)
        //得到公寓配套的id列表
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            ArrayList<ApartmentFacility> apartmentFacilityArrayList = new ArrayList<>();
            facilityInfoIds.forEach(facilityInfoId -> {
                ApartmentFacility apartmentFacility = new ApartmentFacility();
                apartmentFacility.setApartmentId(apartmentSubmitVo.getId());
                apartmentFacility.setFacilityId(facilityInfoId);
                apartmentFacilityArrayList.add(apartmentFacility);
            });
            apartmentFacilityService.saveBatch(apartmentFacilityArrayList);
        }

        //保存公寓标签(关联)
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        if (!CollectionUtils.isEmpty(labelIds)) {
            ArrayList<ApartmentLabel> apartmentLabelArrayList = new ArrayList<>();
            labelIds.forEach(labelId -> {
                ApartmentLabel apartmentLabel = new ApartmentLabel();
                apartmentLabel.setApartmentId(apartmentSubmitVo.getId());
                apartmentLabel.setLabelId(labelId);
                apartmentLabelArrayList.add(apartmentLabel);
            });
            apartmentLabelService.saveBatch(apartmentLabelArrayList);
        }

        //保存公寓杂费值(关联)
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            ArrayList<ApartmentFeeValue> apartmentFeeValueArrayList = new ArrayList<>();
            feeValueIds.forEach(feeValueId -> {
                ApartmentFeeValue apartmentFeeValue = new ApartmentFeeValue();
                apartmentFeeValue.setApartmentId(apartmentSubmitVo.getId());
                apartmentFeeValue.setFeeValueId(feeValueId);
                apartmentFeeValueArrayList.add(apartmentFeeValue);
            });
            apartmentFeeValueService.saveBatch(apartmentFeeValueArrayList);
        }

    }

    @Override
    public void removeApartmentById(Long id) {

        //判断公寓下是否有房间
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId, id);
        long count = roomInfoService.count();
        //count>0,证明该公寓下面还有房间信息
        if (count > 0) {
//            throw new RuntimeException("该公寓下还有房间，请先删除房间信息");
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }

        //删除公寓信息
        this.removeById(id);

        //删除公寓图片(实体)，根据类型和id来删
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType, ItemType.APARTMENT);
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId, id);
        graphInfoMapper.delete(graphInfoLambdaQueryWrapper);
//            graphInfoService.remove(graphInfoLambdaQueryWrapper);

        //删除公寓配套(关联)
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId, id);
        apartmentFacilityMapper.delete(apartmentFacilityLambdaQueryWrapper);

        //删除公寓标签(关联)
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId, id);
        apartmentLabelMapper.delete(apartmentLabelLambdaQueryWrapper);

        //删除公寓杂费值(关联)
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId, id);
        apartmentFeeValueMapper.delete(apartmentFeeValueLambdaQueryWrapper);

    }

    @Override
    public void updateReleaseStatusById(Long id, ReleaseStatus status) {
        LambdaUpdateWrapper<ApartmentInfo> apartmentInfoLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        //组装where语句
        apartmentInfoLambdaUpdateWrapper.eq(ApartmentInfo::getId, id);
        //组装update set语句
        apartmentInfoLambdaUpdateWrapper.set(ApartmentInfo::getIsRelease, status);
        this.update(apartmentInfoLambdaUpdateWrapper);
    }

    /**
     * 根据区域id查询公寓信息列表
     *
     * @param id 区域id
     * @return
     */
    @Override
    public List<ApartmentInfo> listInfoByDistrictId(Long id) {
        LambdaQueryWrapper<ApartmentInfo> apartmentInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentInfoLambdaQueryWrapper.eq(ApartmentInfo::getDistrictId, id);
//        List<ApartmentInfo> list = this.list(apartmentInfoLambdaQueryWrapper);
        List<ApartmentInfo> list = baseMapper.selectList(apartmentInfoLambdaQueryWrapper);
        return list;
    }

    @Override
    public IPage<ApartmentItemVo> pageItem(long current, long size, ApartmentQueryVo queryVo) {
        Page<ApartmentItemVo> page = new Page<>(current, size);
        return baseMapper.pageApartmentItemByQuery(page, queryVo);
    }

    @Override
    public ApartmentDetailVo getApartmentDetailById(Long id) {

        //根据id查询公寓基本信息
        ApartmentInfo apartmentInfo = this.getById(id);
        //健壮性判断
        if (apartmentInfo == null) {
            return null;
        }

        //查询图片列表
        List<GraphVo> graphVoList = graphInfoMapper.selectListByItemTypeAndItemId(ItemType.APARTMENT, id);

        //查询标签列表
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByApartmentId(id);

        //查询配套列表
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectListByApartmentId(id);

        //查询杂费列表
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectListByApartmentId(id);

        //组装最后的数据
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        //组装公寓基本信息
        /*
        该方法主要将一个Java对象的属性值复制到另一个Java对象中，前提是两个对象的属性名
        和类型相匹配，避免了逐个手动调用setter和getter的繁琐操作
         */
        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);
        //组装图片列表
        apartmentDetailVo.setGraphVoList(graphVoList);
        //组装标签列表
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        //组装配套列表
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        //组装杂费列表
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);

        return apartmentDetailVo;
    }

}




